package com.taiyuan.tongcheng.ui;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.kymjs.kjframe.KJHttp;
import org.kymjs.kjframe.http.HttpCallBack;
import org.kymjs.kjframe.http.HttpConfig;
import org.kymjs.kjframe.http.HttpParams;
import org.kymjs.kjframe.ui.AnnotateUtil;
import org.kymjs.kjframe.ui.BindView;
import org.kymjs.kjframe.ui.ViewInject;
import org.kymjs.kjframe.utils.DensityUtils;
import org.kymjs.kjframe.utils.FileUtils;
import org.kymjs.kjframe.utils.KJLoger;
import org.kymjs.kjframe.utils.StringUtils;
import org.kymjs.kjframe.utils.SystemTool;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Point;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.AnticipateOvershootInterpolator;
import android.view.animation.TranslateAnimation;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import cn.jpush.android.api.JPushInterface;

import com.alibaba.fastjson.JSON;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BaiduMap.OnMapStatusChangeListener;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.CityInfo;
import com.baidu.mapapi.search.core.PoiInfo;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.geocode.GeoCodeResult;
import com.baidu.mapapi.search.geocode.GeoCoder;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeOption;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;
import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu;
import com.jeremyfeinstein.slidingmenu.lib.app.SlidingFragmentActivity;
import com.taiyuan.tongcheng.application.AppConfig;
import com.taiyuan.tongcheng.application.AppContext;
import com.taiyuan.tongcheng.bean.ServerStation;
import com.taiyuan.tongcheng.bean.SupportCityInfo;
import com.taiyuan.tongcheng.bean.UpdateInfo;
import com.taiyuan.tongcheng.config.TcConfig;
import com.taiyuan.tongcheng.db.TcDbHelper;
import com.taiyuan.tongcheng.http.HTTPFieldConstant;
import com.taiyuan.tongcheng.http.HttpParamUtil;
import com.taiyuan.tongcheng.http.TcWebservice;
import com.taiyuan.tongcheng.http.WebData;
import com.taiyuan.tongcheng.jsonparser.TcJsParser;
import com.taiyuan.tongcheng.ui.fragment.MenuLeftFragment;
import com.taiyuan.tongcheng.util.ACache;
import com.taiyuan.tongcheng.util.CommonUtil;
import com.taiyuan.tongcheng.util.DialogUtil;
import com.taiyuan.tongcheng.util.L;
import com.taiyuan.tongcheng.util.SharePreferenceUtil;
import com.taiyuan.tongcheng.util.TcUtil;
import com.taiyuan.tongcheng.widget.ImageTextButton;
import com.taiyuan.tongcheng.widget.ProgressWheel;
import com.taiyuan.tongcheng.widget.dialog.TcBuilder;
import com.tytc56.user.R;

public class MainActivitySlide extends SlidingFragmentActivity implements
		OnClickListener, OnMapStatusChangeListener,OnGetGeoCoderResultListener,BDLocationListener {
	// 初始化widget
	@BindView(id = R.id.btn_moving, click = true)
	private ImageTextButton movingBtn; // 搬家按钮
	@BindView(id = R.id.btn_cargo, click = true)
	private ImageTextButton cargoBtn; // 货运按钮
	@BindView(id = R.id.mapview_main)
	private MapView baiduMapView; // 百度地图
	@BindView(id=R.id.btn_account,click=true)
	private Button topSlideBtn;
	@BindView(id=R.id.btn_tel,click=true)
	private Button topCallBtn;
	@BindView(id=R.id.tv_point_info)
	private TextView  pointTv  ;
	@BindView(id=R.id.tv_point_near)
	private TextView  pointNearTv;
	@BindView(id=R.id.img_location)
	private ImageView mLocaImg;
	//侧滑
	private SlidingMenu menu ;
	private Fragment mContent;  
	private Boolean isFirstLoc=false;
	
	
	// 定位相关
	@BindView(id=R.id.btn_center_location,click=true)
	private Button locatBtn;//定位按钮
	private BaiduMap  mapControl;
	private LocationClient   mLocClient;
	private BitmapDescriptor mCurrentMarker;
	private MarkerOptions    markerOptions;
	private GeoCoder geoCoder;
	private BDLocation currentLocation;
	private Boolean isShowDialog=true;
	//
	private SharePreferenceUtil spUtil;
	private Intent movingIntent;
	private Intent expressIntent;
	
	//本页内的定位信息
	private ServerStation startInfo=new ServerStation();
	//flag
	public static final String LABLE_START_STA = "START_STA";
	private boolean isOnKeyBacking;//再按一次退出
	private final Handler mMainLoopHandler = new Handler(
	            Looper.getMainLooper());
	
	//本地缓存
	private ACache  acache;
	//登录intent
	private Intent loginIntent;
	//定位通知框
	private  Dialog  TcLoaddingDialog;
	private  TcBuilder tcInformDialog; 
	private  TcBuilder tcNetWorkDialog; 
	private  TcBuilder telDialog; 
	private KJHttp kjDownhttp;
	// 下载显示控件
	private TextView processMes;
	private TextView processAll;
	private TextView processInfo;
	private Button cancelBtn;
	private int updateCount = 0;
	private TcBuilder upInformDialog;

   // 当前下载进度
	private long totalsize;
	private long currentsize;
	private Dialog dialog;
	private int progress;
	private Dialog loaddingDialog;
	private UpdateInfo appInfo;
	private ProgressWheel progressBar;
	public static final int SHOW_PROGRESS = 0;
	
	private Handler tcHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case SHOW_PROGRESS:

				if (currentsize > 0) {
					processMes.setText(msg.arg1 + "%");
					processAll.setText(currentsize + "/" + totalsize + "M");
				}
				
				break;

			default:
				break;
			}
		}

	};
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main_slide);
		AnnotateUtil.initBindView(this);
		spUtil=new SharePreferenceUtil(getApplicationContext(), AppConfig.SHARE_NAME);
		loginIntent=new Intent(this,LoginActivity.class);
		loginIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		spUtil.setRegistrationID(JPushInterface.getRegistrationID(getApplicationContext()));
		acache=ACache.get(this);
		tcInformDialog=TcBuilder.getInstance(this,1).withTitle("提示").withButton1Text("确定");
		tcInformDialog.setCancelable(false);
		initView();
		initData();
		initMap();
		initSlideMenu(savedInstanceState);
		kjDownhttp=new KJHttp();
		if(initNet()){
			loaddingDialog = DialogUtil.getLoginDialog(this);
			initDownloadDialog(this);
			upInformDialog = TcBuilder.getInstance(this, 1);
			update();
			if(acache.getAsString(TcConfig.IntentTag.CACHE_CITYINFO)!=null){
			}else{
				getSupportCity();
			}
		}
	
	}
    
	
	
	/**
	 * 
	 * @Description: 检测当前网络状态
	 * @return void
	 * @throws
	 * @autour wzq
	 * @date 2015-9-15 下午12:43:44
	 * @update (date)
	 */
	private boolean initNet() {
		
		if(!SystemTool.checkNet(getApplicationContext())){
			tcNetWorkDialog=TcBuilder.getInstance(MainActivitySlide.this,1).withTitle("提示").withContent("未接入到互联网，请检查网络配置！").withButton1Text("取消").withButton2Text("设置").setButton1Click(new OnClickListener() {
				@Override
				public void onClick(View v) {
					tcNetWorkDialog.dismiss();
				}
			}).setButton2Click(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					if(android.os.Build.VERSION.SDK_INT > 10) {
						// 3.0以上打开设置界面，也可以直接用ACTION_WIRELESS_SETTINGS打开到wifi界面 
						startActivity(new Intent( android.provider.Settings.ACTION_SETTINGS)); 
						} else { 
						startActivity(new Intent( android.provider.Settings.ACTION_WIRELESS_SETTINGS)); 
						}
					tcNetWorkDialog.dismiss();
				}
			});
			
			tcNetWorkDialog.show();
			pointNearTv.setText("获取位置信息失败！");
			return false;
		}else{
			return true;
		}

	}

	private void initMap() {
		mapControl=baiduMapView.getMap();
		// 初始化搜索模块，注册事件监听
		geoCoder = GeoCoder.newInstance();
		baiduMapView.showScaleControl(false);
		baiduMapView.showZoomControls(false);
		geoCoder.setOnGetGeoCodeResultListener(this);
		mapControl.setOnMapStatusChangeListener(this);// 增加监听
	
		if(acache.getAsObject("Latitude")!=null&&acache.getAsObject("Longitude")!=null){
			 LatLng cenpt = new LatLng((Double)acache.getAsObject("Latitude"),(Double)acache.getAsObject("Longitude")); 
		        //定义地图状态
			 MapStatus mMapStatus = new MapStatus.Builder()
		        .target(cenpt)
		        .zoom(16)
		        .build();
		        //定义MapStatusUpdate对象，以便描述地图状态将要发生的变化
		        MapStatusUpdate mMapStatusUpdate = MapStatusUpdateFactory.newMapStatus(mMapStatus);
		    	mapControl.animateMapStatus(mMapStatusUpdate);
		}else{
			MapStatusUpdate u = MapStatusUpdateFactory.zoomTo(16);
			mapControl.animateMapStatus(u);
		}
		
		//===定位
		mapControl.setMyLocationEnabled(true);		// 开启定位图层
		mLocClient = new LocationClient(getApplicationContext());// 定位初始化
		mLocClient.registerLocationListener(this);
		LocationClientOption option = new LocationClientOption();
		option.setOpenGps(true);// 打开gps
		option.setCoorType("bd09ll"); // 设置坐标类型
		option.setScanSpan(1000);
		option.setAddrType("all");		// 设置返回类型，all = 表示返回所有的数据
		mLocClient.setLocOption(option);
		mLocClient.start();
//		L.v("证书", SystemTool.getSign(getApplicationContext(), "com.tytc56.user"));
	}

	private void initData() {
		movingIntent=new Intent(new Intent(this, MovingActivity.class));
		expressIntent=new Intent(new Intent(this, ExpressActivity.class));
	}

	private void animation(View v) {
		AnimationSet animationSet = new AnimationSet(true);
		TranslateAnimation translateAnimation = new TranslateAnimation(
				Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF,0,
				Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, -0.35f);
		translateAnimation.setInterpolator(new AnticipateOvershootInterpolator());
		translateAnimation.setFillBefore(true);
		translateAnimation.setDuration(450);
		translateAnimation.setRepeatCount(3);
		translateAnimation.setRepeatMode(Animation.REVERSE);
		animationSet.addAnimation(translateAnimation);
		v.startAnimation(animationSet);
	}
	
	private void initView() {
		movingBtn.setImgResource(R.drawable.selector_home_moving);
		movingBtn.setText(getString(R.string.main_moving_title));
		movingBtn.setTextColor(getResources().getColor(R.color.tcps_color_home_moving));
		cargoBtn.setImgResource(R.drawable.selector_home_cargo);
		cargoBtn.setText(getString(R.string.main_taxi_title));
		cargoBtn.setTextColor(getResources().getColor(R.color.tcps_color_home_cargo));
	}
	
	  
	private void initSlideMenu(Bundle savedInstanceState) {
		
		 if (savedInstanceState != null) {  
	            mContent = getSupportFragmentManager().getFragment(  
	                    savedInstanceState, "mContent");  
	        }  
		 
		 if (mContent == null) {  
	            mContent = new  MenuLeftFragment();  
	        } 

		// configure the SlidingMenu
		menu = getSlidingMenu();
		menu.setMode(SlidingMenu.LEFT);
		menu.setTouchModeAbove(SlidingMenu.TOUCHMODE_NONE);
		menu.setShadowWidthRes(R.dimen.shadow_width);
		menu.setShadowDrawable(R.drawable.shadow);

		// menu.setBehindOffsetRes(R.dimen.slidingmenu_offset);
		menu.setFadeDegree(0.35f);
		menu.setBehindWidth(DensityUtils.getScreenW(this)*770/1080);//

		/**
		 * SLIDING_WINDOW will include the Title/ActionBar in the content
		 * section of the SlidingMenu, while SLIDING_CONTENT does not.
		 */
		setBehindContentView(R.layout.layout_menu_frame);
		MenuLeftFragment leftMenuFragment = new MenuLeftFragment();
		getSupportFragmentManager().beginTransaction()
				.replace(R.id.id_left_menu_frame, mContent).commit();

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_moving:
            if(checkLogin()){
            	Bundle bundle=new Bundle();
				bundle.putSerializable(LABLE_START_STA, startInfo);
				movingIntent.putExtras(bundle);
            	startActivity(movingIntent);
            }	
			break;
		case R.id.btn_cargo:
			if(checkLogin()){
				Bundle bundle=new Bundle();
				bundle.putSerializable(LABLE_START_STA, startInfo);
				expressIntent.putExtras(bundle);
				startActivity(expressIntent);
			}
			break;
			
		case R.id.btn_account:
			  if(checkLogin()){
	            	getSlidingMenu().showMenu();
	           }	
			break;
			
		case R.id.btn_center_location:
				isFirstLoc = true;
				mLocClient.start();
			break;
		case R.id.btn_tel:
//			 Intent intent=new Intent(Intent.ACTION_CALL,Uri.parse("tel:"+TcConfig.HOT_LINE));
//		     startActivity(intent); 
			telDialog= TcBuilder.getInstance(MainActivitySlide.this,1).withButton1Text("确定").withButton2Text("取消").withContent("是否确定拨打人工热线？").withTitle("提示").setButton1Click(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					Intent intent = new Intent(Intent.ACTION_DIAL,Uri.parse("tel:"+ TcConfig.HOT_LINE));
					intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
					startActivity(intent);
					telDialog.dismiss();
				}
			}).setButton2Click(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					telDialog.dismiss();
				}
			});
			telDialog.show();
			
			break;
		default:
			break;
		}
	}

	@Override
	public void onGetGeoCodeResult(GeoCodeResult arg0) {
		
	}

	@Override
	public void onGetReverseGeoCodeResult(ReverseGeoCodeResult result) {
		if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {
			ViewInject.toast("未能找到结果");
			return;
		}
		
		if(result.getPoiList()!=null&&result.getPoiList().size()>0){
			PoiInfo info=result.getPoiList().get(0);
			for (int i = 0; i < result.getPoiList().size(); i++) {
				KJLoger.debug(result.getPoiList().get(i).name);
			}
			
			startInfo.setLatitude(info.location.latitude);
			startInfo.setLongitude(info.location.longitude);
			startInfo.setPlace(info.name);
			startInfo.setCity(spUtil.getLocationCity());
			startInfo.setProvince(result.getAddressDetail().province);
			startInfo.setCityCode(spUtil.getLocationCityCode());
			if(TcDbHelper.getUser(getApplicationContext())!=null){
				startInfo.setReceiver(TcDbHelper.getUser(getApplicationContext()).getName());
				startInfo.setReceiverMobile(TcDbHelper.getUser(getApplicationContext()).getMobile());
			}
			pointTv.setText(info.name);
			pointNearTv.setText(info.address);
		}
	}

	@Override
	public void onMapStatusChange(MapStatus arg0) {
		
	}

	@Override
	public void onMapStatusChangeFinish(MapStatus arg0) {
		animation(mLocaImg);
	}

	@Override
	public void onMapStatusChangeStart(MapStatus arg0) {
        try {
        	LatLng currentLat = mapControl.getProjection().fromScreenLocation(
    				new Point(AppContext.screenW/2,AppContext.screenH/2));
    		geoCoder.reverseGeoCode(new ReverseGeoCodeOption()
    		.location(currentLat));
		} catch (Exception e) {
		}
	}

	@Override
	public void onReceiveLocation(final BDLocation location) {//定位
		// map view 销毁后不在处理新接收的位置
		if (location == null || baiduMapView == null)
			return;
		currentLocation=location;
		
		MyLocationData locData = new MyLocationData.Builder()
				.accuracy(location.getRadius())
				// 此处设置开发者获取到的方向信息，顺时针0-360
				.direction(100).latitude(location.getLatitude())
				.longitude(location.getLongitude()).build();
		mapControl.setMyLocationData(locData);
		
		acache.put("Latitude", location.getLatitude());
		acache.put("Longitude", location.getLongitude());
//		KJLoger.debug(location.getAddrStr()+
//				"=="+location.getLocType());
		if (isFirstLoc) {
			if(isShowDialog){
				final SupportCityInfo info=TcDbHelper.getCityInfoByCity(getApplicationContext(),location.getCity());
				if(info!=null){
					tcInformDialog.withContent("当前定位到"+location.getCity());
					spUtil.setLocationCity(location.getCity());
					spUtil.setLocationProvice(info.getProvinceName());
					spUtil.setLocationCityCode(info.getCode());
				}else{
//					tcInformDialog.withContent("当前定位到"+location.getCity());
					tcInformDialog.withContent("当前定位到"+location.getCity()+"!暂未开通服务,敬请期待！");
					spUtil.setLocationCity(location.getCity());
				}
				
				tcInformDialog.setButton1Click(new OnClickListener() {
					
					@Override
					public void onClick(View v) {
						if(info!=null){
							spUtil.setLocationCity(location.getCity());
							spUtil.setLocationProvice(info.getProvinceName());
							spUtil.setLocationCityCode(info.getCode());
						}else{
							
						}
						tcInformDialog.dismiss();
					}
				});
				tcInformDialog.show();
				isShowDialog=false;
			}
			
			isFirstLoc = false;
			LatLng ll = new LatLng(location.getLatitude(),
					location.getLongitude());
			MapStatusUpdate u = MapStatusUpdateFactory.newLatLng(ll);
			mapControl.animateMapStatus(u);
			geoCoder.reverseGeoCode(new ReverseGeoCodeOption().location(ll));
		}
	}
	
	
	  private final Runnable onBackTimeRunnable = new Runnable() {
	        @Override
	        public void run() {
	            isOnKeyBacking = false;
	        }
	    };
	
	 @Override
	    public boolean onKeyDown(int keyCode, android.view.KeyEvent event) {
	        if (keyCode == KeyEvent.KEYCODE_BACK) {
	            if (isOnKeyBacking) {
	                mMainLoopHandler.removeCallbacks(onBackTimeRunnable);
	                isOnKeyBacking = false;
	                // UIHelper.toHome(aty);
	               MainActivitySlide.this.finish();
	            } else {
	                isOnKeyBacking = true;
	                showExitTip();
	                mMainLoopHandler.postDelayed(onBackTimeRunnable, 2000);
	            }
	            return true;
	        } else {
	            return super.onKeyDown(keyCode, event);
	        }
	    }

	private void showExitTip() {
		showCustomToast("");	
	};

	
	/** 显示自定义Toast提示(来自String) **/
	private void showCustomToast(String text) {
		View toastRoot = LayoutInflater.from(this).inflate(
				R.layout.layout_common_toast, null);
		((TextView) toastRoot.findViewById(R.id.toast_text)).setText(getText(R.string.main_exit_agin));
		Toast toast = new Toast(this);
		toast.setGravity(Gravity.BOTTOM, 0, 100);
		toast.setDuration(Toast.LENGTH_SHORT);
		toast.setView(toastRoot);
		toast.show();
	}
	
/**
 * 
* @Description: 检测登录和网络设置
* @return
* @return boolean
* @throws
* @autour wzq
* @date 2015-9-15 下午1:09:03
* @update (date)
 */
	private boolean  checkLogin() {
		if(initNet()){
			if(spUtil.getLoginFlag()==1){
				return true;
			}else{
				startActivity(loginIntent);
				return false;
			}
		}else{
			return false;
		}
		
	}
	
	/**
	 * 
	* @Description: 获取城市支持
	* @return void
	* @throws
	* @autour Administrator
	* @date 2015-9-5 下午10:53:35 
	* @update (date)
	 */
	private void getSupportCity() {
		HttpConfig config = new HttpConfig();
		config.cacheTime = 0;
        KJHttp kjHttp =new KJHttp(config);
        HttpParams  httpPrams =new HttpParams();
        httpPrams=HttpParamUtil.getSupportCity(this);
        kjHttp.post(TcWebservice.WEBSERVER_IP+TcWebservice.API.APP_SUPPORT, httpPrams, new HttpCallBack() {

			@Override
			public void onFailure(int errorNo, String strMsg) {
				super.onFailure(errorNo, strMsg);
			}
			
			@Override
			public void onSuccess(String t) {
				super.onSuccess(t);
				String json;
				try {
					json = URLDecoder.decode(t,"UTF-8");
					WebData webData=TcJsParser.getWedataData(json);
					List<SupportCityInfo> cityInfoList =new ArrayList<SupportCityInfo>();
					List<String> stringList=new ArrayList<String>();
					stringList=JSON.parseArray(webData.getData(), String.class);
					if(stringList.size()>0){
						TcDbHelper.deleteCityInfo(getApplicationContext());
						for (String string : stringList) {
							SupportCityInfo city=JSON.parseObject(string, SupportCityInfo.class);
							TcDbHelper.saveCityInfo(getApplicationContext(), city);
							cityInfoList.add(city);
						}
					}
					acache.put(TcConfig.IntentTag.CACHE_CITYINFO, webData.getData(),8600);
					
					KJLoger.debug(json);
					acache.put("CITY_SUPPORT",new JSONArray(webData.getData()) , 600000);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}
	
	/**
	 * 
	 * @Description: APP
	 * @return void
	 * @throws
	 * @autour wzq
	 * @date 2015-9-22 下午6:59:53
	 * @update (date)
	 */
	private void update() {
		HttpConfig config = new HttpConfig();
		config.cacheTime = 0;
		KJHttp kjhttp = new KJHttp(config);
		HttpParams params = new HttpParams();
		params.put(HTTPFieldConstant.POST_PARAMS_COMMON_ACT,
				TcUtil.getApiName(TcWebservice.API.APP_UPDATA));
		params.put(HTTPFieldConstant.POST_PARAMS_ACCOUNT_ROLE, 1);
		params.put(HTTPFieldConstant.POST_PARAMS_ACCOUNT_FROM, "1");
		params.put(HTTPFieldConstant.POST_PARAMS_ACCOUNT_DEVID,
				CommonUtil.getAndroidDeviceUnique(this));
		params.put(HTTPFieldConstant.POST_PARAMS_ACCOUNT_VER,
				SystemTool.getAppVersionCode(this));

		kjhttp.post(TcWebservice.WEBSERVER_IP + TcWebservice.API.APP_UPDATA,
				params, new HttpCallBack() {
					@Override
					public void onFailure(int errorNo, String strMsg) {
						super.onFailure(errorNo, strMsg);

					}

					@Override
					public void onSuccess(String t) {
						super.onSuccess(t);
						try {
							String webdateString = URLDecoder
									.decode(t, "UTF-8");
							KJLoger.debug(webdateString);
							WebData data = TcJsParser
									.getWedataData(webdateString);
							if (data.getStatus() == 1) {
								UpdateInfo appInfo = JSON.parseObject(
										data.getData(), UpdateInfo.class);
								KJLoger.debug(appInfo.toString());
								JSONObject obj = new JSONObject(data.getData());
								int a = obj.optInt("vCode", 1);
								if (a > SystemTool
										.getAppVersionCode(getApplicationContext())) {
									showAppUpdataDialog(appInfo);
								}else{
//									showCustomToast("已是最新版本");
									isFirstLoc=true;
									
								}
							} else {
//								showErroCustomToast(data.getMsg());
							}

						} catch (UnsupportedEncodingException e) {
							e.printStackTrace();
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}

					}

				});
	}
	
	/**
	 * 
	 */
	

	private void showAppUpdataDialog(final UpdateInfo appInfo) {
		StringBuilder bulder = new StringBuilder();
		String[] updataContent = {};
		if (!StringUtils.isEmpty(appInfo.getUpdateLog())) {
			List<String> upString = JSON.parseArray(appInfo.getUpdateLog(),
					String.class);
			for (int i = 0; i < upString.size(); i++) {
				bulder.append(upString.get(i));
			}
		}
		upInformDialog.withTitle("同成配送V" + appInfo.getVer())
				.withButton1Text("暂不升级").withContent(bulder.toString())
				.withButton2Text("立刻升级").setButton1Click(new OnClickListener() {

					@Override
					public void onClick(View v) {
						upInformDialog.cancel();
						isFirstLoc=true;
						mLocClient.start();
					}
				}).setButton2Click(new OnClickListener() {

					@Override
					public void onClick(View v) {
						dialog.show();
						download(appInfo.getUrl());
						upInformDialog.cancel();
					}
				});
		upInformDialog.show();
	}
	
	private void download(String url) {

		// loaddingDialog.show();
		final File folder = FileUtils.getSaveFolder(AppConfig.saveFolder);
		File tempFile = new File(folder + "/tcps.apk.tmp");
		if (tempFile.exists()) {
			tempFile.delete();
		}
		kjDownhttp.download(folder + File.separator + AppConfig.ApkName, url,
				new HttpCallBack() {

					/**
					 * 下载过程
					 */
					@Override
					public void onLoading(long count, long current) {
						super.onLoading(count, current);
						KJLoger.debug("count=" + count + "=current=" + current);
						totalsize = count;
						currentsize = current;
						if (updateCount == 0
								|| (current * 100 / count - 2) >= updateCount) {
							updateCount += 2;
							Message msg = new Message();
							msg.obtain();
							msg.what = SHOW_PROGRESS;
							msg.arg1 = updateCount;
							tcHandler.sendMessage(msg);

						}

					}

					/**
					 * 下载完成，开始安装
					 */
					@Override
					public void onSuccess(byte[] t) {
						super.onSuccess(t);
						// loaddingDialog.dismiss();
						dialog.cancel();
						SystemTool.installApk(getApplicationContext(),
								new File(folder + File.separator
										+ AppConfig.ApkName));
					}
				});
	}

	
	/**
	 * 
	 * @Description: 初始化下载弹框
	 * @return void
	 * @throws
	 * @autour wzq
	 * @date 2015-9-23 下午4:49:39
	 * @update (date)
	 */
	private void initDownloadDialog(Context context) {
		dialog = new Dialog(MainActivitySlide.this, R.style.dialog_tran);
		dialog.setCanceledOnTouchOutside(false);
		dialog.setCancelable(false);
		LayoutInflater inflater = (LayoutInflater) context
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		View vi = inflater.inflate(R.layout.layout_download_dialog, null);
		processMes = (TextView) vi.findViewById(R.id.process_msg);
		processAll = (TextView) vi.findViewById(R.id.process_all);
		cancelBtn = (Button) vi.findViewById(R.id.btn_inform_cancel);
		progressBar = (ProgressWheel) vi.findViewById(R.id.progress_wheel);
		cancelBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				dialog.cancel();
				kjDownhttp.cancelAll();
				isFirstLoc=true;
			}
		});
		dialog.setContentView(vi);
	}
	
	
}
